<template>
  <div class="flex flex-col w-full relative transition-opacity duration-300">
    <!-- 骨架屏 -->
    <template v-if="internalLoading || props.loading">
      <div class="flex">
        <!-- 保持和真实数据完全一致的布局 -->
        <div class="flex gap-[2px]">
          <div
            v-for="monthIndex in 12"
            :key="monthIndex"
            class="flex gap-[2px]"
            :style="{ marginRight: monthIndex < 12 ? '6px' : '0' }"
          >
            <!-- 使用真实布局的周数据 -->
            <div
              v-for="weekIndex in 5"
              :key="weekIndex"
              class="grid grid-rows-7 gap-[2px]"
            >
              <div
                v-for="dayIndex in 7"
                :key="dayIndex"
                :style="{
                  width: `${cellSize}px`,
                  height: `${cellSize}px`,
                }"
                class="rounded-[2px] animate-pulse bg-gray-200"
              ></div>
            </div>
          </div>
        </div>
      </div>

      <!-- 月份标题骨架屏 -->
      <div class="flex mt-2">
        <div
          v-for="(month, monthIndex) in months"
          :key="month"
          :style="{
            width: `${getMonthWidth(month)}px`,
            marginRight: monthIndex < 11 ? '6px' : '0',
            textAlign: 'center',
            paddingRight: monthIndex < 11 ? '6px' : '0',
          }"
          class="text-[14px] animate-pulse bg-gray-200 rounded h-6"
        ></div>
      </div>
    </template>

    <!-- 实际内容 -->
    <template v-else>
      <!-- 贡献图表 -->
      <div class="flex">
        <div class="flex gap-[2px]">
          <div
            v-for="(month, monthIndex) in processedData"
            :key="monthIndex"
            class="flex gap-[2px]"
            :style="{ marginRight: monthIndex < 11 ? '6px' : '0' }"
          >
            <div
              v-for="(week, weekIndex) in month"
              :key="`${monthIndex}-${weekIndex}`"
              class="grid grid-rows-7 gap-[2px]"
            >
              <div
                v-for="(day, dayIndex) in week"
                :key="`${monthIndex}-${weekIndex}-${dayIndex}`"
                :style="{
                  width: `${cellSize}px`,
                  height: `${cellSize}px`,
                  visibility: day.visible ? 'visible' : 'hidden',
                }"
                class="rounded-[2px] transition-colors duration-200"
                :class="getContributionClass(day.count)"
              >
                <a-tooltip>
                  <template #title>
                    {{ formatDate(day.date) }}
                    {{ getTooltipText(day.count) }}
                  </template>
                  <div class="w-full h-full"></div>
                </a-tooltip>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 月份标题 -->
      <div class="flex mt-2">
        <div
          v-for="(month, monthIndex) in months"
          :key="month"
          :style="{
            width: `${getMonthWidth(month)}px`,
            marginRight: monthIndex < 11 ? '6px' : '0',
            textAlign: 'center',
            paddingRight: monthIndex < 11 ? '6px' : '0', // 补偿右边距的影响
          }"
          class="text-[14px] text-gray-500"
        >
          {{ month }}月
        </div>
      </div>
    </template>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick } from "vue";
import { Tooltip as ATooltip, Spin as ASpin } from "ant-design-vue";

const props = defineProps({
  year: {
    type: Number,
    required: true,
  },
  recordType: {
    type: String,
    required: true,
    validator: (value) => ["problems", "logins"].includes(value),
  },
  contributionData: { // 新增 prop
    type: Array,
    required: true,
  },
  loading: {
    type: Boolean,
    default: false
  }
});

const cellSize = 10;
const months = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"];

// 根据贡献数量返回对应的颜色类名
const getContributionClass = (count) => {
  if (count === 0) return "bg-gray-200";  // 加深未贡献的颜色
  if (count <= 3) return "bg-green-200";  // 加深最浅的绿色
  if (count <= 6) return "bg-green-400";  // 加深中等的绿色
  if (count <= 9) return "bg-green-600";  // 加深较深的绿色
  return "bg-green-800";                   // 加深最深的绿色
};

// 修改计算每月宽度的方法
const getMonthWidth = (month) => {
  const date = new Date(props.year, parseInt(month) - 1, 1);
  const daysInMonth = new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
  const firstDay = date.getDay();
  const weeksInMonth = Math.ceil((daysInMonth + firstDay) / 7);
  return weeksInMonth * (cellSize + 2); // 使用格子大小加间距
};

// 格式化日期
const formatDate = (date) => {
  return new Date(date).toLocaleDateString("zh-CN", {
    year: "numeric",
    month: "long",
    day: "numeric",
    weekday: "long",
  });
};

// 修改处理贡献数据的方法
const processContributionData = () => {
  console.log('处理数据:', props.contributionData); // 添加日志
  const data = [];

  // 确保有数据
  if (!Array.isArray(props.contributionData)) {
    console.warn('贡献数据格式不正确');
    return Array(12).fill().map(() => []);
  }

  for (let month = 0; month < 12; month++) {
    const monthData = [];
    const date = new Date(props.year, month, 1);
    const daysInMonth = new Date(props.year, month + 1, 0).getDate();
    const firstDayOfMonth = date.getDay();

    let currentWeek = Array(7).fill(null).map(() => ({ visible: false }));
    let weekData = [];

    // 填充实际日期
    for (let day = 1; day <= daysInMonth; day++) {
      const currentDate = new Date(props.year, month, day);
      const dayOfWeek = currentDate.getDay();
      const dateStr = formatDateToString(currentDate); // 使用新的日期格式化方法
      
      // 查找当前日期的贡献数据
      const dayData = props.contributionData.find(d => d.date === dateStr);

      currentWeek[dayOfWeek] = {
        date: currentDate,
        count: dayData ? dayData.count : 0,
        visible: true,
      };

      if (dayOfWeek === 6 || day === daysInMonth) {
        weekData.push([...currentWeek]);
        currentWeek = Array(7).fill().map(() => ({ visible: false }));
      }
    }

    monthData.push(...weekData);
    data.push(monthData);
  }

  return data;
};

// 添加日期格式化方法
const formatDateToString = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

const getTooltipText = (count) => {
  if (props.recordType === "problems") {
    return count > 0 ? `完成 ${count} 个题目` : "未完成题目";
  }
  return count > 0 ? `登录 ${count} 次` : "未登录";
};

const processedData = ref([]);
const internalLoading = ref(true); // 添加内部加载状态

// 优化数据处理方法
const updateData = async () => {
  internalLoading.value = true;
  try {
    await nextTick();
    // 增加延迟时间，让骨架屏效果更明显
    await new Promise(resolve => setTimeout(resolve, 300));
    processedData.value = processContributionData();
  } finally {
    internalLoading.value = false;
  }
};

// 修改监听逻辑
watch(
  [() => props.year, () => props.contributionData],
  async ([newYear, newData]) => {
    if (Array.isArray(newData)) {
      await updateData();
    }
  },
  { immediate: true }
);

onMounted(() => {
  processedData.value = processContributionData();
});
</script>

<style scoped>
.contribution-cell {
  transition: all 0.2s ease;
}

.contribution-cell:hover {
  transform: scale(1.1);
}

:deep(.contribution-grid) {
  width: 100%;
  overflow-x: auto;
}

/* 添加月份文字居中样式 */
.text-xs {
  white-space: nowrap;
  display: inline-block;
}

/* 添加过渡效果 */
.contribution-grid-enter-active,
.contribution-grid-leave-active {
  transition: opacity 0.3s ease;
}

.contribution-grid-enter-from,
.contribution-grid-leave-to {
  opacity: 0;
}

/* 添加渐变过渡效果 */
.opacity-transition {
  transition: opacity 0.3s ease-in-out;
}

/* 更新骨架屏动画 */
@keyframes skeletonPulse {
  0% { opacity: 0.7; }
  50% { opacity: 0.4; }
  100% { opacity: 0.7; }
}

.animate-pulse {
  animation: skeletonPulse 1.5s cubic-bezier(0.4, 0, 0.6, 1) infinite;
}
</style>
